package recordVod 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.NetConnection;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import recordVod.events.EventData;
	import flash.net.Responder;	
	import flash.utils.*;

	
	/**
	 * ...
	 * @author Bamboo
	 */
	public class ConnectFMS  extends EventDispatcher {
		private var _connectGame:NetConnection;
		private var _connectGameRoomId:NetConnection;
		
		private var _clientObject:Object;
		private var _clientObjectRoomId:Object;
		
		private var _fmsPath:String;
		private var _roomId:String;
		private var _userType:String;
		private var _userId:String;
		private var _userPassword:String;
		private var _betLtdSeq:String;
		private var _sessionId:String;
		private var _lang:String;
		private var _versionNo:String;
		private var _forceReload:String;
		private var _isMain:String;
		private var _siteName:String;
		private var _casinoID:String;
		private var _ncName:String;
		private var _ip:String;
		private var _countryCode:String;
		private var _loginTypeID:String;
		private var _parentSID:String;
		private var _keno:String;
		private var timeoutConnect:uint;
		private var intervalConnect:uint;
		private var checkConnect:Boolean = false;
		
		public function ConnectFMS() {
			_connectGame = new NetConnection();
			_connectGameRoomId = new NetConnection();
			_clientObject = new Object();
			_clientObjectRoomId = new Object();
		}
		//define flash media server path
		public function set setFmsPath(value:String):void {
			this._fmsPath = value;
		}
		public function get getFmsPath():String {
			return this._fmsPath;
		}
		//define roomid
		public function set setRoomId(value:String):void {
			this._roomId = value;
		}
		public function get getRoomId():String {
			return this._roomId;
		}
		// define user type
		public function set setUserType(value:String):void {
			this._userType = value;
		}
		public function get getUserType():String {
			return this._userType;
		}
		//define user id
		public function set setUserId(value:String):void {
			this._userId = value;
		}
		public function get getUserId():String {
			return this._userId;
		}
		//define user password
		public function set setUserPassword(value:String):void {
			this._userPassword = value;
		}
		public function get getUserPassword():String {
			return this._userPassword;
		}
		//define BetLtdSeq
		public function set setBetLtdSeq(value:String):void {
			this._betLtdSeq = value;
		}
		public function get getBetLtdSeq():String {
			return this._betLtdSeq;
		}
		//define Session id
		public function set setSessionId(value:String):void {
			this._sessionId = value;
		}
		public function get getSessionId():String {
			return this._sessionId;
		}
		//define language
		public function set setLanguage(value:String):void {
			this._lang = value;
		}
		public function get getLanguage():String {
			return this._lang;
		}
		//define Version Number
		public function set setVersionNo(value:String):void {
			this._versionNo = value;
		}
		public function get getVersionNo():String {
			return this._versionNo;
		}
		//define ForceReload
		public function set setForceReload(value:String):void {
			this._forceReload = value;
		}
		public function get getForceReload():String {
			return this._forceReload;
		}
		//define isMain
		public function set setIsMain(value:String):void {
			this._isMain = value;
		}
		public function get getIsMain():String {
			return this._isMain;
		}
		//define site Name
		public function set setSiteName(value:String):void {
			this._siteName = value;
		}
		public function get getSiteName():String {
			return this._siteName;
		}
		//defin casino Id
		public function set setCasinoId(value:String):void {
			this._casinoID = value;
		}
		public function get getCasinoId():String {
			return this._casinoID;
		}
		//define ncName
		public function set setNcName(value:String):void {
			this._ncName= value;
		}
		public function get getNcName():String {
			return this._ncName;
		}
		//define ip
		public function set setIp(value:String):void {
			this._ip = value;
		}
		public function get getIp():String {
			return this._ip;
		}
		//define country code
		public function set setCountryCode(value:String):void {
			this._countryCode = value;
		}
		public function get getCountryCode():String {
			return this._countryCode;
		}
		//define  type login id
		public function set setLoginTypeId(value:String):void {
			this._loginTypeID = value;
		}
		public function get getLoginTypeId():String {
			return this._loginTypeID;
		}
		//define parentSID
		public function set setParentSID(value:String):void {
			this._parentSID = value;
		}
		public function get getParentSID():String {
			return this._parentSID;
		}
		//define keno game
		public function set setKeno(value:String):void {
			this._keno = value;
		}
		public function get getKeno():String {
			return this._keno;
		}
		
		//do connect FMS
		public function getConnect():void {
			checkConnect = false;
			this._clientObject["setSessionToken"] = setSessionToken;
			this._clientObject["logMeOut"] = logMeout;
		
			this._connectGame.connect(("rtmp://" + this.getFmsPath + "/" + this.getRoomId), this.getUserType, this.getUserId, this.getUserPassword, 
			this.getBetLtdSeq, this.getSessionId, this.getLanguage, this.getVersionNo, this.getForceReload, this.getIsMain, this.getSiteName,
			this.getCasinoId, this.getNcName, this.getIp, this.getCountryCode, this.getLoginTypeId, this.getParentSID);
			
			this._connectGame.client = _clientObject;
			this._connectGame.addEventListener(NetStatusEvent.NET_STATUS, netStatusNcHdl);
			this._connectGame.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHdl);
			timeoutConnect = setTimeout(loginFail,15000);
		}
		
		private function loginFail():void {
			if (!checkConnect) {
				var evt:EventData = new EventData(EventData.SEND_STATUS_CONNECT, true);
				evt.ms = "NetConnection.Connect.Failed";
				dispatchEvent(evt);
			}
		}
		
		public function getConnectId():void {
			trace("getConnectId");
			this._clientObjectRoomId["confirmedConnection"] = confirmedConnection;
			this._clientObjectRoomId["stopBet"] = setStopBet;
			this._clientObjectRoomId["startBet"] = setStarBet;
			this._clientObjectRoomId["setGameDate"] = setGameDate;
			this._clientObject["logMeOut"] = logMeout;
            this._connectGameRoomId.connect(("rtmp://" + this.getFmsPath + "/" + this.getRoomId), this.getUserType, this.getUserId, this.getSessionId, 
			this.getBetLtdSeq, this.getSessionId, this.getLanguage, this.getVersionNo, this.getForceReload, this.getIsMain, this.getSiteName,
			this.getCasinoId, this.getNcName, this.getIp, this.getCountryCode, this.getLoginTypeId, this.getParentSID);
			
			this._connectGameRoomId.client = _clientObjectRoomId;
			this._connectGameRoomId.addEventListener(NetStatusEvent.NET_STATUS, netStatusNcIdHdl);
			this._connectGameRoomId.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHdl);
		}
		
		private function setGameDate(result:String, isNew:String):void 
		{
			
			if (result.substr(0, 1) == "0") {
				var res:String = result.substr(1, result.length);
				var temp:Array = res.split("*");
				var e:EventData = new EventData(EventData.SET_GAME_DATE, true);
				e.result = temp[3];
				dispatchEvent(e);
			}
		}
		
		
		
		
		private function logMeout(res:String):void 
		{
			trace("logMeout" + res);
			this._connectGameRoomId.close();
			this._connectGame.close();
			var evt:EventData = new EventData(EventData.CLOSE_LOGIN, true);
			evt.ms = res;
			dispatchEvent(evt);
		}
		
		
		private function netStatusNcHdl(e:NetStatusEvent):void {
			
			var evt:EventData = new EventData(EventData.SEND_STATUS_CONNECT, true);
			evt.ms = e.info.code;
			dispatchEvent(evt);
			
			checkConnect = true;
			clearTimeout(timeoutConnect);
			trace("netStatusNcHdl:" + e.info.code);
			GlobalVariables.statusConnect = e.info.code;
			switch(e.info.code) {
				case "NetConnection.Connect.Success":
					break;
				case "NetConnection.Connect.Failed":
					break;
				case "NetConnection.Connect.Rejected":
					break;
				case "NetConnection.Connect.Closed":
					break;
			}
		}	
		
		private function netStatusNcIdHdl(e:NetStatusEvent):void {		
			
			
			trace("netStatusNcIdHdl:" + e.info.code);
			GlobalVariables.statusConnect = e.info.code;
			switch(e.info.code) {
				case "NetConnection.Connect.Success":
					if (intervalConnect) {
						clearInterval(intervalConnect);
					}
					intervalConnect = setInterval(sendStatus, 600000);
					break;
				case "NetConnection.Connect.Failed":
					break;
				case "NetConnection.Connect.Rejected":
					break;
				case "NetConnection.Connect.Closed":
					logMeout("status");
					break;
			}
		}	
		
		private function sendStatus():void 
		{
			var evt:EventData = new EventData(EventData.SEND_STATUS_CONNECT, true);
			evt.ms = GlobalVariables.statusConnect;
			trace("GlobalVariables.statusConnect:" + GlobalVariables.statusConnect);
			dispatchEvent(evt);
		}
		
		/**
		 * @author Bamboo
		 */
		private function securityErrorHdl(e:SecurityErrorEvent):void {
			trace("SecurityErrorHdl: " + e);
		}	
		
		private function setSessionToken(result:String):void {
			var e:EventData = new EventData(EventData.SET_SESSIONTOKEN, true);
			e.result = result;
			dispatchEvent(e);
			trace("setSessionToken:" + result);
		}
		
		private function confirmedConnection(result:String):void {
			trace("confirmedConnection")
			var e:EventData = new EventData(EventData.CONFIRMED_CONNECTION, true);
			e.result = result;
			dispatchEvent(e);
		}
		
			
		
		private function failCallFMS(status:Object):void {
			for (var p:String in status){
				trace("FAIL CALL FMS:  " + p + ": " + status[p]);
			} 
		}
		
		private function successCallFMS(status:Object):void { 
			
		}	
		
		public function closeConnectNcId():void {
			this._connectGameRoomId.close();
		}
		
		private function setStarBet(result:String, countDownSecond:String):void {		
			trace("start bet game: " + result);
			if(checkResult(result)) {
				var event:EventData = new EventData(EventData.START_GAME, true);				
				event.result = result;
				event.count_down = Number(countDownSecond);
				
				dispatchEvent(event);
			}else {
				checkTokenInvalid(result);
			}
		}
		
		private function setStopBet(result:String):void {
			if(checkResult(result)){
				var event:EventData = new EventData(EventData.STOP_GAME, true);
				event.result = result;				
				dispatchEvent(event);
			}else {
				checkTokenInvalid(result);
			}
		}
		public function checkResult(result:String):Boolean {
			if (result.substr(0, 1) == "0") {
				return true;
			}
			return false;
		}
		
		public  function checkTokenInvalid(res:String):void {
			var temp:String = res.substr(1, res.length);				
			if (temp == "Token Invalid") {								
				logMeout(res);
			}
		}
	}
}